package dao

import (
	"behavior_srv/handler/models"
	"gorm.io/gorm"
)

// StayTimeDAO 停留时间DAO
type StayTimeDAO struct {
	DB *gorm.DB
}

// Create 创建单条停留时间记录
func (dao *StayTimeDAO) Create(stayTime *models.BehaviorStayTimes) error {
	return dao.DB.Create(stayTime).Error
}

// BatchCreate 批量创建停留时间记录
func (dao *StayTimeDAO) BatchCreate(stayTimes []*models.BehaviorStayTimes) error {
	return dao.DB.CreateInBatches(stayTimes, 100).Error
}

// GetByUserID 获取指定用户的停留时间记录
func (dao *StayTimeDAO) GetByUserID(userID int64, limit, offset int) ([]*models.BehaviorStayTimes, error) {
	var stayTimes []*models.BehaviorStayTimes
	query := dao.DB.Where("user_id = ?", userID).Order("created_at DESC")
	if limit > 0 {
		query = query.Limit(limit).Offset(offset)
	}
	err := query.Find(&stayTimes).Error
	return stayTimes, err
}

// CountByUserID 统计指定用户的停留时间记录数量
func (dao *StayTimeDAO) CountByUserID(userID int64) (int64, error) {
	var count int64
	err := dao.DB.Model(&models.BehaviorStayTimes{}).Where("user_id = ?", userID).Count(&count).Error
	return count, err
}

// GetByPageURL 获取指定页面URL的停留时间记录
func (dao *StayTimeDAO) GetByPageURL(pageURL string, limit, offset int) ([]*models.BehaviorStayTimes, error) {
	var stayTimes []*models.BehaviorStayTimes
	query := dao.DB.Where("page_url = ?", pageURL).Order("created_at DESC")
	if limit > 0 {
		query = query.Limit(limit).Offset(offset)
	}
	err := query.Find(&stayTimes).Error
	return stayTimes, err
}

// GetAverageStayTimeByPageURL 计算指定页面URL的平均停留时间
func (dao *StayTimeDAO) GetAverageStayTimeByPageURL(pageURL string) (int64, error) {
	var avgDuration int64
	err := dao.DB.Model(&models.BehaviorStayTimes{}).
		Select("AVG(stay_duration) as avg_duration").
		Where("page_url = ?", pageURL).
		Scan(&avgDuration).Error
	return avgDuration, err
}
